<template>
  <ContentWrap>
    <el-tabs v-model="activeTab" type="border-card">
      <el-tab-pane label="基础设置" name="basic">
        <el-form ref="formRef" :model="basicFormData" :rules="formRules" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="课程名称" prop="name">
                <el-input v-model="basicFormData.name" placeholder="请输入课程名称" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="课程分类" prop="courseType">
                <el-tree-select
                  ref="treeSelectRef"
                  v-model="basicFormData.courseType"
                  :data="treeData"
                  :props="treeProps"
                  placeholder="请选择课程分类"
                  clearable
                  @click="handleTreeClick"
                  default-expand-all
                  class="custom-tree-select"
                  check-strictly
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="basicFormData.status">
                  <el-radio :value="1">有效</el-radio>
                  <el-radio :value="0">无效</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="封面" prop="cover">
                <div class="upload-container">
                  <el-upload
                    ref="uploadRef"
                    class="cover-uploader"
                    :action="uploadUrl"
                    :headers="headers"
                    :show-file-list="false"
                    :before-upload="beforeAvatarUpload"
                    :auto-upload="true"
                    :http-request="httpRequest"
                    :on-error="handleAvatarError"
                    :on-success="handleAvatarSuccess"
                    accept=".jpg,.png"
                  >
                    <div class="upload-area">
                      <img
                        v-if="basicFormData.cover"
                        :src="basicFormData.cover"
                        class="cover-img"
                      />
                      <template v-else>
                        <el-icon class="upload-icon"><Plus /></el-icon>
                        <span class="upload-text">上传封面</span>
                      </template>
                    </div>
                  </el-upload>
                  <div class="upload-tip">
                    建议尺寸：750x422px，支持 jpg、png 格式，文件小于 2M
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="讲师" prop="teacher">
                <div class="tag-container">
                  <el-tag
                    v-for="teacherId in basicFormData.teacher"
                    :key="teacherId"
                    class="mr-1"
                    closable
                    @close="handleRemoveTeacher(teacherId)"
                  >
                    {{ selectedTeacherInfo.find((t) => t.id === teacherId)?.name }}
                  </el-tag>
                  <el-button link type="primary" @click="openSelectTeacherDialog"
                    >选择讲师
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="课程标签" prop="tags">
                <div class="tag-container">
                  <el-tag
                    v-for="tagId in basicFormData.tags"
                    :key="tagId"
                    class="mr-1"
                    closable
                    @close="handleRemoveCourseTag(tagId)"
                  >
                    {{ tagOptions.find((t) => t.value === tagId)?.label }}
                  </el-tag>
                  <el-button link type="primary" @click="openSelectTagDialog">选择标签</el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="课程有效期" prop="validType">
                <el-radio-group v-model="basicFormData.validType" @change="handleValidTypeChange">
                  <el-radio :value="1">长期有效</el-radio>
                  <el-radio :value="2">
                    按天数
                    <el-tooltip content="从加入当天起，在几天内可进行学习" placement="top">
                      <el-icon class="help-icon"><QuestionFilled /></el-icon>
                    </el-tooltip>
                  </el-radio>
                  <el-radio :value="3">
                    固定周期
                    <el-tooltip content="请选择课程的开始和结束日期" placement="top">
                      <el-icon class="help-icon"><QuestionFilled /></el-icon>
                    </el-tooltip>
                  </el-radio>
                </el-radio-group>

                <!-- 按天数 -->
                <div v-if="basicFormData.validType === 2">
                  <el-form-item
                    label=""
                    prop="validDays"
                    :rules="[{ required: true, message: '请输入有效天数', trigger: 'change' }]"
                    class="valid-days-input"
                  >
                    <el-input-number
                      v-model="basicFormData.validDays"
                      :min="1"
                      style="width: 120px"
                    />
                    <span class="ml-2">天</span>
                  </el-form-item>
                </div>

                <!-- 固定周期 -->
                <div v-if="basicFormData.validType === 3">
                  <el-form-item
                    label=""
                    prop="validPeriod"
                    :rules="[{ required: true, message: '请选择有效期范围', trigger: 'change' }]"
                    class="valid-period-input"
                  >
                    <el-date-picker
                      v-model="basicFormData.validPeriod"
                      type="daterange"
                      unlink-panels
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      :shortcuts="dateShortcuts"
                      style="width: 360px"
                    />
                  </el-form-item>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="课程介绍" prop="teacherIntro">
                <Editor
                  v-model="basicFormData.teacherIntro"
                  :style="{ height: '300px' }"
                  :defaultConfig="{
                    readOnly: false,
                    placeholder: '请输入内容，支持直接粘贴文本和图片',
                    MENU_CONF: {
                      uploadImage: {
                        server: uploadUrl,
                        fieldName: 'file',
                        headers: {
                          Authorization: 'Bearer ' + getAccessToken()
                        },
                        maxFileSize: 10 * 1024 * 1024, // 限制大小为10M
                        allowedFileTypes: ['image/*'],
                        customInsert(res: any, insertFn: Function) {
                          if (res.code === 0 && res.data) {
                            insertFn(res.data)
                          } else {
                            message.error('图片上传失败')
                          }
                        },
                        onError(file: File, err: any) {
                          message.error(`图片 ${file.name} 上传失败: ${err.message}`)
                        }
                      }
                    },
                    pasteFilterStyle: false, // 不过滤粘贴内容的样式
                    pasteIgnoreImg: false, // 不忽略粘贴的图片
                    pasteTextHandle: undefined // 不对粘贴文本做额外处理
                  }"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="课件列表" name="materials">
        <MaterialSelectList @add-material="handleAddMaterial"></MaterialSelectList>
      </el-tab-pane>
      <el-tab-pane label="权限配置" name="permission">
        <el-form label-width="120px">
          <el-form-item label="下载权限">
            <el-radio-group v-model="permissionConfig.downloadPermission">
              <el-radio :value="1">允许下载</el-radio>
              <el-radio :value="0">禁止下载</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="观看权限">
            <div class="permission-row">
              <el-radio-group v-model="permissionConfig.viewPermission">
                <el-radio :value="1">公开</el-radio>
                <el-radio :value="2">指定人员</el-radio>
              </el-radio-group>
              <el-button
                v-if="permissionConfig.viewPermission === 2"
                link
                type="primary"
                @click="openSelectUserDialog"
              >
                指定
              </el-button>
            </div>

            <!-- 添加这部分代码：显示已选择的人员信息 -->
            <div v-if="permissionConfig.viewPermission === 2" class="permission-details">
              <el-descriptions :column="1" border>
                <el-descriptions-item v-if="hasSelectedUsers" label="添加人员">
                  <div class="tags-wrapper">
                    <el-tag
                      v-for="tag in selectedUserTags"
                      :key="tag.id"
                      :class="['permission-tag', `tag-${tag.type}`]"
                      effect="plain"
                      size="small"
                      closable
                      @close="handleRemoveTag('selected', tag)"
                    >
                      <el-icon v-if="tag.type === 'dept'">
                        <OfficeBuilding />
                      </el-icon>
                      <el-icon v-else>
                        <User />
                      </el-icon>
                      {{ tag.name }}
                    </el-tag>
                  </div>
                </el-descriptions-item>

                <el-descriptions-item v-if="hasExcludedUsers" label="排除人员">
                  <div class="tags-wrapper">
                    <el-tag
                      v-for="tag in excludedUserTags"
                      :key="tag.id"
                      :class="['permission-tag', `tag-${tag.type}`]"
                      effect="plain"
                      size="small"
                      type="danger"
                      closable
                      @close="handleRemoveTag('excluded', tag)"
                    >
                      <el-icon v-if="tag.type === 'dept'">
                        <OfficeBuilding />
                      </el-icon>
                      <el-icon v-else>
                        <User />
                      </el-icon>
                      {{ tag.name }}
                    </el-tag>
                  </div>
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="学习防作弊" name="antiCheating">
        <el-form label-width="120px">
          <el-form-item label="是否可倍数播放">
            <el-switch v-model="antiCheatingConfig.multiplePlay" />
          </el-form-item>
          <el-form-item label="视频快进限制">
            <el-switch v-model="antiCheatingConfig.forwardLimit" />
          </el-form-item>
          <el-form-item label="弹窗防呆校验">
            <el-switch v-model="antiCheatingConfig.popupCheck" />
          </el-form-item>
          <el-form-item label="禁止视频拖动">
            <el-switch v-model="antiCheatingConfig.disableDrag" />
          </el-form-item>
          <el-form-item label="顺序学习">
            <el-switch v-model="antiCheatingConfig.orderStudy" />
          </el-form-item>
          <el-form-item label="人脸识别">
            <el-switch v-model="antiCheatingConfig.faceRecognition" />
          </el-form-item>
          <el-form-item label="人脸抓拍">
            <el-switch v-model="antiCheatingConfig.capture" />
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>

    <div class="mt-4 text-center">
      <el-button type="primary" class="save-button" @click="submitForm">保存</el-button>
      <el-button @click="goBack">返回</el-button>
    </div>
  </ContentWrap>

  <!-- 选择标签弹窗 -->
  <el-dialog v-model="selectTagDialogVisible" align-center title="选择标签" width="600px">
    <div class="tag-select-content">
      <div class="dialog-header">
        <el-button type="primary" @click="openAddTagDialog">添加标签</el-button>
      </div>
      <div class="tag-list">
        <el-tag
          v-for="tag in tagOptions"
          :key="tag.value"
          :class="{ 'is-selected': selectedTempTags.includes(tag.value) }"
          class="tag-item"
          @click="toggleTag(tag.value)"
        >
          {{ tag.label }}
          <el-icon class="delete-icon" @click="handleDeleteTag(tag.value, $event)">
            <Close />
          </el-icon>
        </el-tag>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="selectTagDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSelectTags">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 添加标签弹窗 -->
  <el-dialog
    v-model="addTagDialogVisible"
    title="添加标签"
    width="400px"
    @close="handleAddTagDialogClose"
  >
    <el-form :model="newTagForm" :rules="newTagRules" ref="newTagFormRef">
      <el-form-item label="标签名称" prop="name">
        <el-input v-model="newTagForm.name" placeholder="请输入标签名称" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addTagDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAddTag">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 讲师选择弹窗 -->
  <el-dialog v-model="teacherSelectVisible" align-center title="选择教师" width="600px">
    <div class="teacher-select-content">
      <!-- 添加搜索区域 -->
      <div class="search-area">
        <el-input v-model="teacherSearchName" class="search-input" placeholder="根据用户名搜索" />
        <el-input v-model="teacherSearchPhone" class="search-input" placeholder="根据手机号" />
        <el-button type="primary" @click="handleTeacherSearch">搜索</el-button>
      </div>

      <!-- 教师列表 -->
      <el-table
        :data="teacherList"
        style="width: 100%"
        class="mt-2"
        row-key="id"
        ref="teacherTableRef"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          :selectable="(row) => isSelectable(row)"
          :reserve-selection="true"
        />
        <el-table-column label="头像/昵称">
          <template #default="{ row }">
            <div class="teacher-info">
              <el-avatar :size="32" :src="row.avatar">
                {{ row.name?.charAt(0) }}
              </el-avatar>
              <span class="ml-2">{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号码" />
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <span class="total-text">共 {{ total }} 条</span>
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="sizes, prev, pager, next"
          background
          size="small"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="teacherSelectVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSelectTeacher">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 用户选择抽屉 -->
  <el-drawer
    v-model="selectUserDrawerVisible"
    title="指定观看人员"
    direction="rtl"
    size="70%"
    :before-close="handleDrawerClose"
  >
    <div class="drawer-container">
      <!-- 使用新组件 -->
      <UserTagsPanel
        v-model:activeTab="userTabsActive"
        v-model:excludedTags="excludedUserTags"
        v-model:selectedTags="selectedUserTags"
        @change="handleTagsChange"
        @tag-removed="handleTagRemoved"
      />

      <!-- 下部分：用户选择区域 -->
      <el-card class="drawer-section">
        <div class="drawer-layout">
          <!-- 左侧部门树 -->
          <div class="dept-tree-container">
            <el-input
              v-model="deptFilterText"
              placeholder="输入关键字过滤"
              clearable
              class="filter-input"
            />
            <el-tree
              ref="deptTreeRef"
              :data="deptTreeData"
              :props="{
                label: 'name',
                children: 'children'
              }"
              node-key="id"
              highlight-current
              default-expand-all
              show-checkbox
              check-strictly
              :filter-node-method="filterNode"
              @check="handleDeptCheck"
              @node-click="handleDeptNodeClick"
              class="dept-tree"
            />
          </div>

          <!-- 右侧用户列表 -->
          <div class="user-list-container">
            <div class="search-header">
              <el-form :inline="true" :model="userSearchForm">
                <el-form-item label="用户名称">
                  <el-input
                    v-model="userSearchForm.username"
                    placeholder="请输入用户名称"
                    clearable
                    class="!w-240px"
                  />
                </el-form-item>
                <el-form-item label="手机号码">
                  <el-input
                    v-model="userSearchForm.mobile"
                    placeholder="请输入手机号码"
                    clearable
                    class="!w-240px"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleUserSearch">搜索</el-button>
                </el-form-item>
              </el-form>
            </div>

            <el-table
              ref="userTableRef"
              :data="userList"
              v-loading="userLoading"
              style="width: 100%"
              @selection-change="handleUserSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column label="用户编号" align="center" prop="id" />
              <el-table-column
                label="用户名称"
                align="center"
                prop="username"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                label="用户昵称"
                align="center"
                prop="nickname"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                label="部门"
                align="center"
                prop="deptName"
                :show-overflow-tooltip="true"
              />
              <el-table-column label="手机号码" align="center" prop="mobile" width="120" />
            </el-table>

            <div class="pagination-wrapper">
              <el-pagination
                v-model:current-page="userPageParams.pageNo"
                v-model:page-size="userPageParams.pageSize"
                :total="userTotal"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next"
                @size-change="handleUserSizeChange"
                @current-change="handleUserPageChange"
              />
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 添加抽屉底部按钮区域 -->
    <template #footer>
      <div class="drawer-footer">
        <el-button type="primary" @click="handleDrawerClose">确 定</el-button>
      </div>
    </template>
  </el-drawer>

  <!-- 素材选择弹窗 -->
  <MaterialSelectDialog v-model="materialSelectVisible" />
</template>

<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router'
import { ManageApi } from '@/api/lession/manage'
import { getAccessToken } from '@/utils/auth'
import { Close, OfficeBuilding, Plus, QuestionFilled, User } from '@element-plus/icons-vue'
import { useMessage } from '@/hooks/web/useMessage'
import Editor from '@/components/Editor/src/Editor.vue'
import { TeacherApi } from '@/api/lession/teacher'
import { onMounted, ref, watch } from 'vue'
import { ClassifyApi } from '@/api/lession/classify'
import * as DeptApi from '@/api/system/dept'
import * as UserApi from '@/api/system/user'
import { ElMessageBox } from 'element-plus'
import MaterialSelectDialog from './components/MaterialSelectDialog.vue'
import MaterialSelectList from './components/MaterialSelectList.vue'
import { useCentreStore } from '@/store/modules/lession/centre'
import { storeToRefs } from 'pinia'
import UserTagsPanel from './components/UserTagsPanel.vue'
import { useUpload } from '@/components/UploadFile/src/useUpload'
import { useTagsView } from '@/hooks/web/useTagsView'

const router = useRouter()
const route = useRoute()
const message = useMessage()

const centreStore = useCentreStore()
const { basicFormData, permissionConfig, antiCheatingConfig } = storeToRefs(centreStore)

// 表单相关的 ref
const formRef = ref()
const teacherTableRef = ref()

// 当前激活的标签页
const activeTab = ref('basic')

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入课程名称' },
    { min: 1, max: 10, message: '课程名称长度不能超过10个字符', trigger: 'blur' }
  ],
  cover: [{ required: true, message: '请上传封面' }]
}

// 上传相关
const headers = ref({
  Authorization: 'Bearer ' + getAccessToken()
})

const uploadRef = ref()
const { uploadUrl, httpRequest } = useUpload()

const handleAvatarSuccess = (response: any) => {
  if (response.code === 0) {
    basicFormData.value.cover = response.data
    // 手动清除表单验证错误
    formRef.value.clearValidate('cover')
    message.success('上传成功')
  } else {
    message.error('上传失败')
  }
}

const handleAvatarError = () => {
  message.error('上传失败，请重试！')
}

const beforeAvatarUpload = (file: File) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJpgOrPng) {
    message.error('封面图片只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt2M) {
    message.error('封面图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 引入标签页相关的 store
const { closeCurrent } = useTagsView()
// 修改提交表单方法
const submitForm = async () => {
  try {
    // 收集所有错误信息
    const errors: string[] = []

    // 验证基础表单
    try {
      await formRef.value.validate()
    } catch (validationError: any) {
      // 如果是表单验证错误，获取第一个字段的第一个错误信息
      if (validationError.fields) {
        const firstField = Object.values(validationError.fields)[0] as any[]
        if (firstField && firstField.length > 0) {
          errors.push(firstField[0].message)
        }
      }
    }

    // 如果已经有表单验证错误，直接返回第一个错误
    if (errors.length > 0) {
      message.error(errors[0])
      return
    }

    // 验证其他必填项
    if (!basicFormData.value.name) {
      message.error('请输入课程名称')
      return
    }
    if (!basicFormData.value.cover) {
      message.error('请上传封面')
      return
    }
    if (!centreStore.selectedMaterials?.length) {
      message.error('请至少选择一个课件')
      return
    }

    const type = route.query.type as string
    const id = route.query.id as string
    const submitData = centreStore.getFullFormData()

    // 调用 API 保存数据
    try {
      await ManageApi.saveOrUpdate({
        ...submitData,
        id: id ? parseInt(id) : undefined
      })
      console.log('submitData:', JSON.stringify(submitData))
      message.success(type === 'update' ? '修改成功' : '新增成功')
      centreStore.resetAllConfig()
      // 设置需要刷新标记
      centreStore.setNeedRefresh(true)

      // 关闭当前标签页并返回列表页
      closeCurrent(route)
      router.push('/lession/centre')
    } catch (apiError: any) {
      message.error(apiError.message || '保存失败')
    }
  } catch (err: any) {
    // 处理其他类型的错误
    message.error(err.message || '保存失败')
  }
}

// 修改获取详情方法
const getDetail = async (id: number) => {
  try {
    const data = await ManageApi.getManage(id)

    // 确保 tags 是数组类型
    if (data.tags && !Array.isArray(data.tags)) {
      data.tags = [data.tags]
    }

    // 先获取课程分类数据
    await handleTreeClick()

    // 更新 store 中的数据
    centreStore.updateBasicFormData(data)

    // 初始化临时选中标签
    selectedTempTags.value = [...(data.tags || [])]

    // 获取标签列表以显示标签名称
    await getTagList()

    if (data.permission) {
      centreStore.updatePermissionUsers(data.permission)
      // 初始化权限配置标签
      await initPermissionTags()
    }
    if (data.antiCheating) {
      centreStore.setAntiCheatingConfig(data.antiCheating)
    }
    if (data.materials) {
      centreStore.setSelectedMaterials(data.materials)
    }

    // 确保在数据加载完成后设置课程分类的选中状态
    nextTick(() => {
      if (treeSelectRef.value && data.courseType) {
        treeSelectRef.value.setCurrentKey(data.courseType)
      }
    })
  } catch (error) {
    console.error('获取课程详情失败:', error)
    message.error('获取课程详情失败')
  }
}

// 课件相关方法
const handleAddMaterial = () => {
  materialSelectVisible.value = true
}

// 返回列表页
const goBack = () => {
  router.push('/lession/centre')
}

// 初始化
onMounted(async () => {
  const type = route.query.type
  const id = route.query.id as string

  // 先加载课程分类数据
  await handleTreeClick()

  try {
    if (type === 'update' && id) {
      // 编辑模式
      await getDetail(parseInt(id))
      // 如果有已选讲师,初始化讲师信息
      if (basicFormData.value.teacher.length > 0) {
        await initSelectedTeachers()
      }
    }
  } catch (error) {
    console.error('初始化数据失败:', error)
    message.error('初始化数据失败')
  }
})

// 添加标签选项
const tagOptions = ref<{ value: number; label: string }[]>([])

// 修改获取标签列表的方法
const getTagList = async () => {
  try {
    const res = await ManageApi.getLables(1)
    if (Array.isArray(res)) {
      tagOptions.value = res.map((item) => ({
        value: Number(item.id),
        label: item.name
      }))
    } else {
      tagOptions.value = [] // 确保在获取失败时初始化为空数组
      message.error('获取标签列表失败')
    }
  } catch (err) {
    tagOptions.value = [] // 确保在出错时初始化为空数组
    message.error('获取标签列表失败')
  }
}

// 处理有效期类型变更
const handleValidTypeChange = (value: number) => {
  if (value === 2) {
    basicFormData.value.validPeriod = []
  } else if (value === 3) {
    basicFormData.value.validDays = 30
  }
}

// 日期选择器的快捷选项
const dateShortcuts = ref([
  {
    text: '未来一周',
    value: () => {
      const start = new Date()
      const end = new Date()
      end.setTime(end.getTime() + 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '未来一个月',
    value: () => {
      const start = new Date()
      const end = new Date()
      end.setTime(end.getTime() + 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '未来三个月',
    value: () => {
      const start = new Date()
      const end = new Date()
      end.setTime(end.getTime() + 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
])

// 标签相关
const selectTagDialogVisible = ref(false)
const addTagDialogVisible = ref(false)
const selectedTempTags = ref<number[]>([]) // 临时存储选中的标签

// 新标签表单
const newTagFormRef = ref()
const newTagForm = ref({
  name: ''
})
const newTagRules = {
  name: [
    { required: true, message: '请输入标签名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value && tagOptions.value.some((tag) => tag.label === value)) {
          callback(new Error('该标签已存在'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 打开选择标签弹窗
const openSelectTagDialog = async () => {
  try {
    selectTagDialogVisible.value = true

    // 初始化临时选中标签为当前已选标签
    selectedTempTags.value = [...(basicFormData.value.tags || [])]

    // 获取标签列表
    await getTagList()

    // 确保在标签列表加载完成后设置选中状态
    nextTick(() => {
      // 遍历标签列表,设置选中状态
      selectedTempTags.value.forEach((tagId) => {
        const tag = tagOptions.value.find((t) => t.value === tagId)
        if (tag) {
          tag.selected = true
        }
      })
    })
  } catch (error) {
    console.error('打开标签选择失败:', error)
    message.error('打开标签选择失败')
  }
}

// 打开添加标签弹窗
const openAddTagDialog = () => {
  newTagForm.value.name = ''
  // 重置表单验证信息
  if (newTagFormRef.value) {
    newTagFormRef.value.resetFields()
  }
  addTagDialogVisible.value = true
}

// 监听添加标签弹窗的关闭事件
const handleAddTagDialogClose = () => {
  newTagForm.value.name = ''
  // 重置表单验证信息
  if (newTagFormRef.value) {
    newTagFormRef.value.resetFields()
  }
}

// 修改切换标签选中状态的方法
const toggleTag = (tagId: number) => {
  const index = selectedTempTags.value.indexOf(tagId)
  if (index > -1) {
    // 如果已选中，则移除
    selectedTempTags.value.splice(index, 1)
  } else {
    // 如果未选中，检查是否超过限制
    if (selectedTempTags.value.length >= 5) {
      message.warning('最多只能选择5个标签')
      return
    }
    selectedTempTags.value.push(tagId)
  }
  // 同步更新 basicFormData.tags
  basicFormData.value.tags = [...selectedTempTags.value]
}

// 修改确认选择标签的方法
const confirmSelectTags = () => {
  if (selectedTempTags.value.length > 5) {
    message.warning('最多只能选择5个标签')
    return
  }
  basicFormData.value.tags = [...selectedTempTags.value]
  selectTagDialogVisible.value = false
}

// 确认添加标签
const confirmAddTag = async () => {
  await newTagFormRef.value.validate()
  const newTag = newTagForm.value.name

  // 检查标签是否已存在
  const isExist = tagOptions.value.some((tag) => tag.label === newTag)
  if (isExist) {
    message.error('该标签已存在')
    return
  }

  try {
    // 调用添加标签接口
    await ManageApi.addLabel({
      name: newTag
    })

    // 添加成功后重新获取标签列表
    await getTagList()
    message.success('添加标签成功')
    addTagDialogVisible.value = false
  } catch (err) {
    message.error('添加标签失败')
  }
}

// 移除标签
const handleRemoveTag = (
  type: 'selected' | 'excluded',
  tag: {
    id: number
    type: 'user' | 'dept'
  }
) => {
  try {
    console.log('1----:', JSON.stringify(permissionConfig.value))
    // 根据类型选择对应的数组
    const tagsArray = type === 'selected' ? selectedUserTags : excludedUserTags

    // 从数组中移除标签
    const index = tagsArray.value.findIndex((t) => t.id === tag.id && t.type === tag.type)
    if (index > -1) {
      tagsArray.value.splice(index, 1)
    }

    // 如果是部门标签，需要更新树的选中状态
    if (tag.type === 'dept' && deptTreeRef.value) {
      deptTreeRef.value.setChecked(tag.id, false)
    }

    // 如果是用户标签，需要更新表格的选中状态
    if (tag.type === 'user' && userTableRef.value) {
      const row = userList.value.find((user) => user.id === tag.id)
      if (row) {
        userTableRef.value.toggleRowSelection(row, false)
      }
    }

    // 更新 store 中的权限配置
    updateStorePermissionUsers()
    console.log('11----:', JSON.stringify(permissionConfig.value))
    message.success('移除成功')
  } catch (error) {
    console.error('移除标签失败:', error)
    message.error('移除失败')
  }
}

// 添加讲师选项数据
const teacherSelectVisible = ref(false)

// 讲师搜索相关
const teacherSearchName = ref('')
const teacherSearchPhone = ref('')
const teacherList = ref<any[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedTeachers = ref<any[]>([])
const selectedTeacherInfo = ref<any[]>([])

// 搜索相关方法
const handleTeacherSearch = () => {
  currentPage.value = 1
  getTeacherList()
}

// 分页相关方法
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getTeacherList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getTeacherList()
}

// 修改获取讲师列表方法
const getTeacherList = async () => {
  try {
    const res = await TeacherApi.getTeacherPage({
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      name: teacherSearchName.value,
      phone: teacherSearchPhone.value
    })

    if (res && res.list) {
      teacherList.value = res.list
      total.value = res.total

      // 设置已选讲师的选中状态
      nextTick(() => {
        if (teacherTableRef.value) {
          teacherList.value.forEach((teacher) => {
            const isSelected = basicFormData.value.teacher.includes(teacher.id)
            teacherTableRef.value.toggleRowSelection(teacher, isSelected)
          })
        }
      })
    }
  } catch (err) {
    message.error('获取讲师列表失败')
  }
}

// 修改选择讲师确认方法
const confirmSelectTeacher = () => {
  // 更新讲师ID列表
  basicFormData.value.teacher = selectedTeachers.value.map((item) => item.id)

  // 更新讲师详细信息
  selectedTeacherInfo.value = selectedTeachers.value.map((item) => ({
    id: item.id,
    name: item.name || item.nickname, // 添加 nickname 作为备选
    avatar: item.avatar,
    phone: item.phone
  }))

  teacherSelectVisible.value = false
}

// 修改打开选择讲师弹窗方法
const openSelectTeacherDialog = async () => {
  teacherSelectVisible.value = true
  // 重置搜索条件
  teacherSearchName.value = ''
  teacherSearchPhone.value = ''
  currentPage.value = 1

  // 获取讲师列表
  await getTeacherList()
}

// 修改表格选择变更处理方法
const handleSelectionChange = (val: any[]) => {
  selectedTeachers.value = val.map((item) => ({
    id: item.id,
    name: item.name || item.nickname,
    avatar: item.avatar,
    phone: item.phone
  }))
}

// 修改初始化已选讲师信息的方法
const initSelectedTeachers = async () => {
  if (basicFormData.value.teacher.length > 0) {
    try {
      const res = await TeacherApi.getTeacherPage({
        pageNo: 1,
        pageSize: basicFormData.value.teacher.length,
        ids: basicFormData.value.teacher
      })
      if (res && res.list) {
        selectedTeacherInfo.value = res.list.map((item) => ({
          id: item.id,
          name: item.name,
          avatar: item.avatar,
          phone: item.phone
        }))
      }
    } catch (err) {
      message.error('获取讲师信息失败')
    }
  }
}

// 判断是否可选
const isSelectable = (row: any) => {
  return true // 可以根据需求添加选择条件
}

// 获取课程分类数据
const treeData = ref([])
const treeSelectRef = ref()

// 递归构建树形结构，并添加expanded属性
const buildTree = (items: any[], parentId: null | number = null): any[] => {
  const children = items
    .filter((item) => item.parentId === parentId)
    .map((item) => {
      const node = {
        value: item.id,
        label: item.name,
        expanded: true,
        children: buildTree(items, item.id)
      }
      if (node.children.length === 0) {
        delete node.children
      }
      return node
    })
  return children
}

// 修改el-tree-select的props配置
const treeProps = {
  value: 'value',
  label: 'label',
  children: 'children',
  expanded: 'expanded'
}

// 标记是否已加载数据
const hasLoadedTree = ref(false)

// 处理点击展开时的加载
const handleTreeClick = async () => {
  if (!hasLoadedTree.value) {
    try {
      const response = await ClassifyApi.getClassifyList({ type: 1 })
      const tree = buildTree(response)
      treeData.value = tree
      hasLoadedTree.value = true
    } catch (error) {
      message.error('获取课程分类失败')
    }
  }
}

// 用户选择相关
const selectUserDrawerVisible = ref(false)
const userTableRef = ref()
const userList = ref([])
const userTotal = ref(0)

// 搜索表单
const userSearchForm = ref({
  username: '', // 用户名称
  mobile: '', // 手机号码
  status: undefined, // 状态
  deptId: undefined // 单个部门ID
})

// 分页参数
const userPageParams = ref({
  pageNo: 1,
  pageSize: 10
})

// 部门树相关
const deptTreeRef = ref()
const deptFilterText = ref('')
const deptTreeData = ref([])

// 监听部门过滤文本变化
watch(deptFilterText, (val) => {
  deptTreeRef.value?.filter(val)
})

// 部门树过滤方法
const filterNode = (value: string, data: any) => {
  if (!value) return true
  return data.name.includes(value)
}

// 修改获取部门树数据的方法
const getDeptTreeData = async () => {
  try {
    const res = await DeptApi.getSimpleDeptList()
    // 构建树形结构
    deptTreeData.value = buildDeptTree(res)
  } catch (err) {
    message.error('获取部门树失败')
  }
}

// 添加构建部门树的方法
const buildDeptTree = (depts: any[]): any[] => {
  // 创建一个映射表来存储所有部门
  const deptMap = new Map()
  depts.forEach((dept) => {
    deptMap.set(dept.id, { ...dept, children: [] })
  })

  const tree: any[] = []

  // 构建树形结构
  depts.forEach((dept) => {
    const node = deptMap.get(dept.id)
    if (dept.parentId === 0) {
      // 顶级部门
      tree.push(node)
    } else {
      // 子部门
      const parent = deptMap.get(dept.parentId)
      if (parent) {
        parent.children.push(node)
      }
    }
  })

  // 移除空的 children 数组
  const removeEmptyChildren = (nodes: any[]) => {
    nodes.forEach((node) => {
      if (node.children.length === 0) {
        delete node.children
      } else {
        removeEmptyChildren(node.children)
      }
    })
  }
  removeEmptyChildren(tree)

  return tree
}

// 处理部门点击
const handleDeptClick = (data: any) => {
  userSearchForm.value.deptId = data.id
  handleUserSearch()
}

// 修改用户搜索方法
const handleUserSearch = () => {
  userPageParams.value.pageNo = 1 // 重置到第一页
  getUserList() // 刷新用户列表
}

// 修改打开选择用户抽屉方法
const openSelectUserDialog = async () => {
  selectUserDrawerVisible.value = true
  userSearchForm.value.deptId = undefined

  // 获取部门树和用户列表
  await getDeptTreeData()
  await getUserList()

  // 设置选中状态
  nextTick(() => {
    // 设置部门树选中状态
    if (deptTreeRef.value) {
      const deptTags =
        userTabsActive.value === 'include'
          ? selectedUserTags.value.filter((tag) => tag.type === 'dept')
          : excludedUserTags.value.filter((tag) => tag.type === 'dept')

      const deptIds = deptTags.map((tag) => tag.id)
      deptTreeRef.value.setCheckedKeys(deptIds)
    }

    // 设置用户表格选中状态
    if (userTableRef.value) {
      const userTags =
        userTabsActive.value === 'include'
          ? selectedUserTags.value.filter((tag) => tag.type === 'user')
          : excludedUserTags.value.filter((tag) => tag.type === 'user')

      userList.value.forEach((user) => {
        const isSelected = userTags.some((tag) => tag.id === user.id)
        userTableRef.value.toggleRowSelection(user, isSelected)
      })
    }
  })
}

// 添加一个标记来控制是否处理选择变化
const isLoadingPage = ref(false)

// 修改获取用户列表方法
const getUserList = async () => {
  console.log('3----:', JSON.stringify(permissionConfig.value))
  try {
    isLoadingPage.value = true // 标记开始加载页面
    userLoading.value = true
    const params = {
      pageNo: userPageParams.value.pageNo,
      pageSize: userPageParams.value.pageSize,
      username: userSearchForm.value.username,
      mobile: userSearchForm.value.mobile,
      deptId: userSearchForm.value.deptId
    }
    const res = await UserApi.getUserPage(params)
    userList.value = res.list
    userTotal.value = res.total

    // 在数据加载完成后恢复选中状态
    nextTick(() => {
      if (userTableRef.value) {
        // 获取当前标签页对应的用户标签
        const userTags =
          userTabsActive.value === 'include' ? selectedUserTags.value : excludedUserTags.value

        // 只选中当前页面上存在的已选用户
        userList.value.forEach((user) => {
          if (userTags.some((tag) => tag.id === user.id && tag.type === 'user')) {
            userTableRef.value.toggleRowSelection(user, true)
          }
        })
      }
    })
    console.log('33----:', JSON.stringify(permissionConfig.value))
  } catch (err) {
    message.error('获取用户列表失败')
  } finally {
    userLoading.value = false
    setTimeout(() => {
      isLoadingPage.value = false // 标记页面加载完成
    }, 100) // 给一个小延时确保选择状态已经恢复
  }
}

// 修改处理用户选择变化的方法
const handleUserSelectionChange = (selection: any[]) => {
  console.log('4----:', JSON.stringify(permissionConfig.value))
  if (isLoadingPage.value) return

  // 获取当前标签页对应的标签数组引用
  const currentTags = userTabsActive.value === 'include' ? selectedUserTags : excludedUserTags

  // 获取当前页面上的用户ID列表
  const currentPageUserIds = userList.value.map((u) => u.id)

  // 保留不在当前页面的已选标签
  const tagsNotInCurrentPage = currentTags.value.filter(
    (tag) => tag.type !== 'user' || !currentPageUserIds.includes(tag.id)
  )

  // 添加当前页面选中的用户标签
  const newSelectedTags = selection.map((user) => ({
    // 修改这里的变量名，避免命名冲突
    id: user.id,
    name: user.nickname || user.username,
    type: 'user' as const
  }))

  // 合并标签
  currentTags.value = [...tagsNotInCurrentPage, ...newSelectedTags]

  // 实时更新store
  updateStorePermissionUsers()
  console.log('44----:', JSON.stringify(permissionConfig.value))
}

// 修改处理分页的方法
const handleUserPageChange = (val: number) => {
  userPageParams.value.pageNo = val
  getUserList()
}

const handleUserSizeChange = (val: number) => {
  userPageParams.value.pageSize = val
  userPageParams.value.pageNo = 1 // 重置到第一页
  getUserList()
}

// 添加用户列表相关的方法
const userLoading = ref(false)

// 修改处理部门树选择的方法
const handleDeptCheck = async (data: any, { checkedKeys }) => {
  console.log('5----:', JSON.stringify(permissionConfig.value))
  try {
    const isChecking = checkedKeys.includes(data.id)
    const actionText = isChecking ? '选择' : '取消选择'

    if (data.children && data.children.length > 0) {
      try {
        await ElMessageBox.confirm(`是否同时${actionText}所有子部门？`, '提示', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'info'
        })
        const childrenIds = getChildrenIds(data)
        childrenIds.forEach((id) => {
          deptTreeRef.value.setChecked(id, isChecking)
        })
      } catch {
        deptTreeRef.value.setChecked(data.id, isChecking)
      }
    }

    // 更新部门标签
    const checkedNodes = deptTreeRef.value.getCheckedNodes()
    const currentTags = userTabsActive.value === 'include' ? selectedUserTags : excludedUserTags

    // 更新部门标签
    currentTags.value = [
      ...currentTags.value.filter((tag) => tag.type === 'user'), // 保留用户标签
      ...checkedNodes.map((node) => ({
        id: node.id,
        name: node.name,
        type: 'dept' as const
      }))
    ]

    // 实时更新store
    updateStorePermissionUsers()
    console.log('55----:', JSON.stringify(permissionConfig.value))
  } catch (error) {
    console.error('处理部门选择出错:', error)
  }
}

// 添加获取所有子节点ID的方法
const getChildrenIds = (node: any): number[] => {
  const ids: number[] = []
  const traverse = (n: any) => {
    if (n.id) {
      ids.push(n.id)
    }
    if (n.children) {
      n.children.forEach(traverse)
    }
  }
  if (node.children) {
    node.children.forEach(traverse)
  }
  return ids
}

// 修改部门节点点击事件处理器
const handleDeptNodeClick = (data: any) => {
  // 只在点击部门名称时触发用户列表刷新
  userSearchForm.value.deptId = data.id
  handleUserSearch()
}

// 添加tabs相关的响应式数据
const userTabsActive = ref('include')
const selectedUserTags = ref<{ id: number; name: string; type: 'user' | 'dept' }[]>([])
const excludedUserTags = ref<{ id: number; name: string; type: 'user' | 'dept' }[]>([])

// 修改监听标签页切换的方法
watch(userTabsActive, async (newValue) => {
  console.log('6----:', JSON.stringify(permissionConfig.value))

  // 清除表格选择状态前，先记住当前的选择
  const currentSelectedTags = [...selectedUserTags.value] // 创建副本
  const currentExcludedTags = [...excludedUserTags.value] // 创建副本

  if (userTableRef.value) {
    userTableRef.value.clearSelection()
  }

  // 重置并设置部门树选择状态
  if (deptTreeRef.value) {
    // 获取新标签页的部门标签
    const deptTags =
      newValue === 'include'
        ? currentSelectedTags.filter((tag) => tag.type === 'dept')
        : currentExcludedTags.filter((tag) => tag.type === 'dept')

    // 设置树的选中状态
    const deptIds = deptTags.map((tag) => tag.id)
    deptTreeRef.value.setCheckedKeys(deptIds)
  }

  // 等待下一个 tick，确保表格数据已更新
  await nextTick()

  // 恢复表格的选中状态
  if (userTableRef.value) {
    const tagsToRestore =
      newValue === 'include'
        ? currentSelectedTags.filter((tag) => tag.type === 'user')
        : currentExcludedTags.filter((tag) => tag.type === 'user')

    // 确保在当前页面的用户才会被选中
    const currentPageUserIds = userList.value.map((user) => user.id)
    userList.value.forEach((user) => {
      if (tagsToRestore.some((tag) => tag.id === user.id && currentPageUserIds.includes(user.id))) {
        userTableRef.value.toggleRowSelection(user, true)
      }
    })
  }

  console.log('66----:', JSON.stringify(permissionConfig.value))
})

// 添加对搜索表单中用户名和手机号的监听
watch(
  () => [userSearchForm.value.username, userSearchForm.value.mobile],
  ([newUsername, newMobile], [oldUsername, oldMobile]) => {
    // 只在值从有到无的时候刷新
    if ((oldUsername && !newUsername) || (oldMobile && !newMobile)) {
      handleUserSearch()
    }
  }
)

// 添加关闭前的处理方法
const handleDrawerClose = () => {
  // 关闭抽屉时自动保存当前状态
  updateStorePermissionUsers()
  selectUserDrawerVisible.value = false
}

// 移除重复定义的 handleRemoveTeacher 方法,添加新的方法
const handleRemoveTeacher = (teacherId: number) => {
  const index = basicFormData.value.teacher.indexOf(teacherId)
  if (index > -1) {
    basicFormData.value.teacher.splice(index, 1)
    // 同时从已选讲师信息中移除
    const infoIndex = selectedTeacherInfo.value.findIndex((t) => t.id === teacherId)
    if (infoIndex > -1) {
      selectedTeacherInfo.value.splice(infoIndex, 1)
    }
  }
}

// 添加素材选择弹窗的控制变量
const materialSelectVisible = ref(false)

// 格式化素材类型
const formatMaterialType = (type: string) => {
  const typeMap: Record<string, string> = {
    video: '视频',
    document: '文档',
    image: '图片',
    audio: '音频'
    // 添加其他类型映射...
  }
  return typeMap[type] || type
}

// 格式化文件大小
const formatFileSize = (size: number) => {
  if (!size) return '0 B'
  const units = ['B', 'KB', 'MB', 'GB']
  let index = 0
  while (size >= 1024 && index < units.length - 1) {
    size /= 1024
    index++
  }
  return `${size.toFixed(2)} ${units[index]}`
}

// 修改更新store的方法
const updateStorePermissionUsers = () => {
  // 确保在更新store之前保留两个列表的完整性
  const storeUpdate = {
    selectedUsers: selectedUserTags.value.filter((tag) => tag.type === 'user').map((tag) => tag.id),
    selectedDepts: selectedUserTags.value.filter((tag) => tag.type === 'dept').map((tag) => tag.id),
    excludedUsers: excludedUserTags.value.filter((tag) => tag.type === 'user').map((tag) => tag.id),
    excludedDepts: excludedUserTags.value.filter((tag) => tag.type === 'dept').map((tag) => tag.id)
  }

  centreStore.updatePermissionUsers(storeUpdate)
}

// 添加标签变化处理方法
const handleTagsChange = (type: 'selected' | 'excluded', tags: any[]) => {
  console.log('9----:', JSON.stringify(permissionConfig.value))
  // 实时更新 store
  updateStorePermissionUsers()
  console.log('99----:', JSON.stringify(permissionConfig.value))
}

// 使用 store 中的 getters
const { hasSelectedUsers, hasExcludedUsers } = storeToRefs(centreStore)

// 添加删除标签的方法
const handleDeleteTag = async (tagId: number, event: Event) => {
  // 阻止事件冒泡，避免触发标签的点击事件
  event.stopPropagation()

  try {
    await ElMessageBox.confirm('确定要删除该标签吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 调用删除标签接口
    await ManageApi.deleteLabel(tagId)

    // 如果标签已被选中，需要从选中列表中移除
    const index = selectedTempTags.value.indexOf(tagId)
    if (index > -1) {
      selectedTempTags.value.splice(index, 1)
      basicFormData.value.tags = [...selectedTempTags.value]
    }

    // 重新获取标签列表
    await getTagList()
    message.success('删除标签成功')
  } catch (err) {
    if (err !== 'cancel') {
      message.error('删除标签失败')
    }
  }
}

// 添加新的方法
const handleRemoveCourseTag = (tagId: number) => {
  try {
    // 从基础表单数据中移除标签
    const index = basicFormData.value.tags.indexOf(tagId)
    if (index > -1) {
      basicFormData.value.tags.splice(index, 1)
    }

    // 同时从临时选中标签中移除
    const tempIndex = selectedTempTags.value.indexOf(tagId)
    if (tempIndex > -1) {
      selectedTempTags.value.splice(tempIndex, 1)
    }

    message.success('移除标签成功')
  } catch (error) {
    console.error('移除课程标签失败:', error)
    message.error('移除标签失败')
  }
}

// 添加处理标签移除的方法
const handleTagRemoved = (
  type: 'selected' | 'excluded',
  tag: {
    id: number
    type: 'user' | 'dept'
  }
) => {
  // 如果是用户标签，需要更新表格的选中状态
  if (tag.type === 'user' && userTableRef.value) {
    const row = userList.value.find((user: any) => user.id === tag.id)
    if (row) {
      userTableRef.value.toggleRowSelection(row, false)
    }
  }

  // 如果是部门标签，需要更新树的选中状态
  if (tag.type === 'dept' && deptTreeRef.value) {
    deptTreeRef.value.setChecked(tag.id, false)
  }

  // 更新 store 中的权限配置
  updateStorePermissionUsers()
}

// 添加监听 basicFormData.tags 的变化
watch(
  () => basicFormData.value.tags,
  (newTags) => {
    // 当 tags 发生变化时,同步更新临时选中标签
    selectedTempTags.value = [...(newTags || [])]
  }
)

// 添加监听课程分类变化
watch(
  () => basicFormData.value.courseType,
  (newValue) => {
    if (newValue && treeSelectRef.value) {
      nextTick(() => {
        treeSelectRef.value.setCurrentKey(newValue)
      })
    }
  }
)

// 修改 initPermissionTags 方法
const initPermissionTags = async () => {
  try {
    // 获取已选用户信息
    if (permissionConfig.value.selectedUsers?.length) {
      const selectedUsers = await UserApi.getUserList({
        ids: permissionConfig.value.selectedUsers
      })
      selectedUserTags.value = selectedUsers.map((user) => ({
        id: user.id,
        name: user.nickname || user.username,
        type: 'user' as const
      }))
    }

    // 获取已选部门信息
    if (permissionConfig.value.selectedDepts?.length) {
      const selectedDepts = await UserApi.getDeptList({
        ids: permissionConfig.value.selectedDepts
      })
      selectedUserTags.value.push(
        ...selectedDepts.map((dept) => ({
          id: dept.id,
          name: dept.name,
          type: 'dept' as const
        }))
      )
    }

    // 获取排除用户信息
    if (permissionConfig.value.excludedUsers?.length) {
      const excludedUsers = await UserApi.getUserList({
        ids: permissionConfig.value.excludedUsers
      })
      excludedUserTags.value = excludedUsers.map((user) => ({
        id: user.id,
        name: user.nickname || user.username,
        type: 'user' as const
      }))
    }

    // 获取排除部门信息
    if (permissionConfig.value.excludedDepts?.length) {
      const excludedDepts = await UserApi.getDeptList({
        ids: permissionConfig.value.excludedDepts
      })
      excludedUserTags.value.push(
        ...excludedDepts.map((dept) => ({
          id: dept.id,
          name: dept.name,
          type: 'dept' as const
        }))
      )
    }
  } catch (error) {
    console.error('初始化权限配置失败:', error)
    message.error('初始化权限配置失败')
  }
}
</script>

<style scoped>
.mt-2 {
  margin-top: 8px;
}
.mt-4 {
  margin-top: 16px;
}
.text-center {
  text-align: center;
}
.cover-uploader {
  :deep(.el-upload) {
    display: block;
  }

  .upload-area {
    width: 240px;
    height: 135px;
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-color: var(--el-fill-color-lighter);
  }

  .upload-area:hover {
    border-color: var(--el-color-primary);
    .upload-icon {
      color: var(--el-color-primary);
    }
    .upload-text {
      color: var(--el-color-primary);
    }
  }

  .upload-icon {
    font-size: 28px;
    color: #8c939d;
    margin-bottom: 8px;
  }

  .upload-text {
    color: #8c939d;
    font-size: 14px;
  }

  .cover-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

:deep(.w-e-text-container) {
  background-color: #fff !important;
  border: 1px solid var(--el-border-color) !important;
  border-top: none !important;
}

:deep(.w-e-toolbar) {
  background-color: #fff !important;
  border: 1px solid var(--el-border-color) !important;
}

.upload-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.upload-tip {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  line-height: 1.5;
}

.valid-days-input {
  margin-left: 20px;
  :deep(.el-form-item__content) {
    display: flex;
    align-items: center;
  }
}

.valid-period-input {
  margin-left: 20px;
  :deep(.el-form-item__content) {
    display: flex;
    align-items: center;
  }
}

.ml-2 {
  margin-left: 8px;
}

.help-icon {
  margin-left: 4px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
  cursor: help;
}

.help-icon:hover {
  color: var(--el-color-primary);
}

.tag-container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}

.mr-1 {
  margin-right: 4px;
}

.tag-select-content {
  padding: 20px;
  min-height: 200px;
  max-height: 70vh;
  display: flex;
  flex-direction: column;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 10px;
  overflow-y: auto;
  flex: 1;
}

.tag-item {
  cursor: pointer;
  user-select: none;
  font-size: 14px;
  padding: 0 24px 0 12px;
  height: 32px;
  line-height: 30px;
  position: relative;
}

.tag-item:hover {
  border-color: var(--el-color-primary);
  color: var(--el-color-primary);
}

:deep(.el-tag.is-selected) {
  background-color: var(--el-color-primary);
  border-color: var(--el-color-primary);
  color: white;
}

:deep(.el-tag.is-selected:hover) {
  background-color: var(--el-color-primary-light-3);
  border-color: var(--el-color-primary-light-3);
  color: white;
}

/* 移除之前的一些不需要的样式 */
.mx-1,
.mb-2,
.cursor-pointer {
  display: none;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

/* 删除不需要的样式 */
.selected-tags,
.tag-actions {
  display: none;
}

.dialog-header {
  margin-bottom: 20px;
}

.save-button {
  width: 120px;
}

.delete-icon {
  position: absolute;
  right: 2px;
  top: 2px;
  transform: none;
  font-size: 12px;
  cursor: pointer;
  transition: color 0.2s;
  z-index: 1;
  width: 14px;
  height: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
}

.delete-icon:hover {
  color: var(--el-color-danger);
  background-color: rgba(0, 0, 0, 0.1);
}

:deep(.el-dialog__footer) {
  padding-top: 10px;
  margin-top: 0;
  border-top: 1px solid var(--el-border-color-lighter);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding: 10px 20px;
}

.teacher-select-content {
  padding: 20px;
  height: calc(100vh - 300px);
  display: flex;
  flex-direction: column;
}

.teacher-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 10px;
}

.teacher-item {
  cursor: pointer;
  user-select: none;
  font-size: 14px;
  padding: 0 12px;
  height: 32px;
  line-height: 30px;
}

.teacher-item:hover {
  border-color: var(--el-color-primary);
  color: var(--el-color-primary);
}

:deep(.el-tag.is-selected) {
  background-color: var(--el-color-primary);
  border-color: var(--el-color-primary);
  color: white;
}

:deep(.el-tag.is-selected:hover) {
  background-color: var(--el-color-primary-light-3);
  border-color: var(--el-color-primary-light-3);
  color: white;
}

.search-area {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.search-input {
  width: 200px;
}

.teacher-info {
  display: flex;
  align-items: center;
}

.pagination-container {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 12px;
  padding: 0;
}

.total-text {
  color: var(--el-text-color-secondary);
  font-size: 13px;
}

:deep(.el-pagination) {
  --el-pagination-button-height: 28px;

  .el-pager {
    padding: 0;
    margin: 0 8px;
  }

  .el-pagination__sizes {
    margin: 0 8px 0 0;
  }

  .btn-prev {
    margin-right: 0;
  }

  .btn-next {
    margin-left: 0;
  }

  .el-select {
    --el-select-input-width: 90px;
  }
}

:deep(.el-dialog__body) {
  padding: 0;
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* 添加自定义树选择器样式 */
.custom-tree-select {
  :deep(.el-select-dropdown__wrap) {
    max-height: none !important; /* 移除最大高度限制 */
  }

  :deep(.el-scrollbar__wrap) {
    overflow-x: hidden !important; /* 隐藏水平滚动条 */
    margin-bottom: 0 !important;
  }

  :deep(.el-select-dropdown__list) {
    padding: 4px 0;
  }

  :deep(.el-tree) {
    /* 确保树的容器不会出现滚动条 */
    overflow: hidden !important;
  }
}

.permission-row {
  display: flex;
  align-items: center;
  gap: 12px;
}

.drawer-content {
  padding: 20px;
}

.search-area {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.search-item {
  width: 200px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.drawer-layout {
  height: 100%;
  gap: 16px;
  display: flex;
}

.dept-tree-container {
  width: 250px;
  border-right: 1px solid var(--el-border-color-light);
  padding-right: 20px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  height: 100%;
}

.filter-input {
  margin-bottom: 12px;
}

.dept-tree {
  flex: 1;
  overflow: auto;
}

.user-list-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  position: relative;
  padding-bottom: 48px;
}

.search-header {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.search-input {
  width: 200px;
}

/* 确保表格在容器中正确滚动 */
.el-table {
  flex: 1;
  height: 0;
  overflow: auto;
  margin-bottom: 8px;
}

/* 调整分页器样式 */
.pagination-container {
  margin-top: 16px;
  padding: 0;
}

.mb-4 {
  margin-bottom: 16px;
}

:deep(.el-card) {
  margin-bottom: 16px;

  &:last-child {
    margin-bottom: 0;
  }
}

:deep(.el-tabs__nav-wrap::after) {
  height: 1px;
}

:deep(.el-tabs__item) {
  font-size: 14px;
  height: 40px;
  line-height: 40px;
}

:deep(.el-tabs__active-bar) {
  height: 2px;
}

/* 调整内容区域的滚动 */
:deep(.el-drawer__body) {
  padding: 0;
  overflow-y: auto;
}

:deep(.el-card__body) {
  padding: 12px;
  display: flex;
  flex-direction: column;
  height: 100%;

  /* 上面卡片的内容区域 */

  .drawer-section:first-child & {
    height: auto;
    overflow: auto;
  }

  /* 下面卡片的内容区域 */

  .drawer-section:last-child & {
    height: 100%;
    overflow: hidden;
  }
}

/* 新增和修改的样式 */
.drawer-container {
  height: calc(100%);
  padding: 8px;
  background-color: var(--el-bg-color-page);
  display: flex;
  flex-direction: column;
  overflow: hidden; /* 防止溢出 */
}

.drawer-section {
  background-color: var(--el-bg-color);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
  display: flex;
  flex-direction: column;
  overflow: hidden; /* 防止溢出 */

  &:first-child {
    flex: 0 0 auto;
    margin-bottom: 8px;
  }

  &:last-child {
    flex: 1 1 auto;
    min-height: 0; /* 允许内容收缩 */
  }
}

/* 修改 el-card__body 的样式 */
:deep(.el-card__body) {
  padding: 12px;
  display: flex;
  flex-direction: column;
  height: 100%;

  /* 上面卡片的内容区域 */

  .drawer-section:first-child & {
    height: auto;
    overflow: auto;
  }

  /* 下面卡片的内容区域 */

  .drawer-section:last-child & {
    height: 100%;
    overflow: hidden;
  }
}

/* 确保抽屉布局正确 */
.drawer-layout {
  height: 100%;
  gap: 16px;
  display: flex;
  overflow: hidden;
}

/* 确保用户列表容器正确显示 */
.user-list-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  position: relative;
  padding: 0px;
}

/* 确保表格正确滚动 */
.el-table {
  flex: 1;
  height: 0;
  overflow: auto;
  margin-bottom: 8px;
}

/* 添加新的标签样式 */
:deep(.tag-dept) {
  --el-tag-bg-color: var(--el-color-success-light-9);
  --el-tag-border-color: var(--el-color-success-light-5);
  --el-tag-text-color: var(--el-color-success);
}

:deep(.tag-user) {
  --el-tag-bg-color: var(--el-color-primary-light-9);
  --el-tag-border-color: var(--el-color-primary-light-5);
  --el-tag-text-color: var(--el-color-primary);
}

/* 添加新的样式 */
.permission-details {
  margin: 0;
  width: 24px;
  width: 100%;
}

.tags-wrapper {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 8px;
  min-height: 40px;
  position: relative;
  width: 100%;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 4px;
  background-color: var(--el-fill-color-blank);
  margin-bottom: 0px;
}

/* 修改描述列表样式 */
:deep(.el-descriptions) {
  width: 100%;
}

:deep(.el-descriptions__cell) {
  padding: 0;
}

:deep(.el-descriptions__label) {
  width: 100px;
  margin-left: 0;
  padding: 0;
}

:deep(.el-descriptions__content) {
  padding: 0;
}

/* 修改标签组件样式 */
:deep(.el-tag) {
  margin: 0;
  transition: none !important; /* 移除标签的过渡效果 */
}

/* 标签页样式 */
:deep(.el-tabs__nav) {
  position: relative;
  z-index: 1;
}

:deep(.el-tabs__item) {
  padding: 0 20px;
  height: 40px;
  line-height: 40px;
  transition: none !important; /* 移除标签页的过渡效果 */
}

/* 移除所有可能影响布局的过渡效果 */
:deep(.el-descriptions),
:deep(.el-descriptions__body),
:deep(.el-descriptions__table),
:deep(.el-descriptions__cell),
:deep(.el-descriptions__content),
:deep(.el-descriptions-item__container) {
  transition: none !important;
}

/* 确保标签容器不会因为内容变化而改变大小 */
:deep(.el-descriptions__content) {
  min-height: 60px;
  height: auto !important;
  padding: 12px;
}

/* 优化标签组样式 */
:deep(.tag-dept),
:deep(.tag-user) {
  display: inline-flex;
  align-items: center;
  margin: 2px 4px;
  position: relative;
  transition: none !important; /* 移除过渡效果 */

  .el-tag__close {
    position: relative;
    top: 0;
    right: 0;
  }
}

/* 移除之前添加的动画相关样式 */
.tag-transition-enter-active,
.tag-transition-leave-active,
.tag-transition-enter-from,
.tag-transition-leave-to {
  display: none;
}

/* 优化抽屉内容布局 */
.drawer-container {
  height: calc(100% - 0px);
  padding: 8px;
  background-color: var(--el-bg-color-page);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.drawer-section {
  background-color: var(--el-bg-color);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
  display: flex;
  flex-direction: column;

  &:first-child {
    flex: 0 0 auto;
    margin-bottom: 8px;
  }

  &:last-child {
    flex: 1 1 auto;
  }
}

/* 确保内容区域稳定 */
:deep(.el-descriptions__body) {
  width: 100%;
}

:deep(.el-descriptions__table) {
  width: 100%;
  table-layout: fixed;
}

/* 移除可能导致布局跳动的样式 */
.permission-tag {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  margin: 0;
  position: static;

  :deep(.el-icon) {
    margin-right: 2px;
  }

  &:hover {
    transform: none;
    box-shadow: none;
  }
}

/* 确保标签内容稳定显示 */
:deep(.el-tag__content) {
  display: inline-flex;
  align-items: center;
  white-space: nowrap;
}
</style>
